<template>
  <div class="data-text">
    <el-input
      :rows="8"
      placeholder="请输入内容"
      v-model="text"
      @change="syncValue"
      type="textarea"
      clearable>
    </el-input>
  </div>
</template>

<script>
import columns from '../constant/key-value-columns.js'
import utils from './utils.js'

export default {
  props: {
    columns: {
      default () {
        return columns
      }
    },
    value: {
      default () {
        return []
      }
    }
  },

  model: {
    prop: 'value'
  },

  data () {
    return {
      text: ''
    }
  },

  watch: {
    value: {
      deep: true,
      handler () {
        this.refresh()
      }
    }
  },

  mounted () {
    this.refresh()
  },

  methods: {
    refresh () {
      let list = this.value, columns = this.columns
      let valc = columns.find(item => item.forField === 'value') || {}
      list = list.filter(item => {
        return (item.key || item.value)
      })
      list = list.map(item => {
        let key = String(item.key).trim(), val = item.value
        if (key && !/^\d+/.test(key)) {
          val = utils.formatValue(val, item[valc.field])
        }
        if (item.required === false) {
          key = '//' + key
        }
        return key + ':' + val
      })
      this.text = list.join('\n')
    },
    syncValue () {
      let text = this.text, list = this.value
      let rows = text.split(/\n+|\r+/)
      rows = rows.filter(item => !!item || !/^\s*\{\s*|\s*\}\s*$/.test(item))
      rows = rows.map((item, i) => {
        let symbol = item.indexOf(':')
        symbol = symbol === -1 ? item.length : symbol
        let key = item.slice(0, symbol).trim()
        let val = item.slice(symbol + 1).replace(/\,\s*$/, '').trim()
        let required = true
        if (/^\s*\/\/\s*/.test(key)) {
          key = key.replace(/^\s*\/\/\s*/, '')
          required = false
        }
        let node = {key: key, value: val, description: (list[i] || {}).description || '', required: required}
        // 含有类型
        if (this.columns.find(item => item.field === 'type')) {
          node.type = (list[i] || {}).type || 'string'
        }
        return node
      })
      if (rows.length < list.length) {
        let last = list[rows.length]
        if (!last.key && !last.value && last.description) {
          rows.push(last)
        }
      }
      this.value.splice(0, this.value.length, ...rows)
    }
  }
}
</script>

<style lang="less" scoped>

</style>